package com.sdkj.recruit.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.sdkj.recruit.common.Constants;
import com.sdkj.recruit.model.ResultCode;
import com.sdkj.recruit.model.ResultData;
import com.sdkj.recruit.model.User;
import com.sdkj.recruit.model.UserDeviceAccess;
import com.sdkj.recruit.service.IQiNiuService;
import com.sdkj.recruit.service.IShareService;
import com.sdkj.recruit.service.IUserService;
import com.sdkj.recruit.util.DESEncryption;
import com.sdkj.recruit.util.FileUploadUtil;
import com.sdkj.recruit.util.FileUploadUtil.UploadFileItem;
import com.sdkj.recruit.util.ImageUtil;
import com.sdkj.recruit.util.MD5Util;
import com.sdkj.recruit.util.PropertiesUtil;
import com.sdkj.recruit.util.RandomUtil;
import com.sdkj.recruit.util.RequestUtils;
import com.sdkj.recruit.util.StringUtil;
import com.sdkj.recruit.vo.CompanyResumeVo;
import com.sdkj.recruit.vo.EducationalExperienceVo;
import com.sdkj.recruit.vo.ResumeVo;
import com.sdkj.recruit.vo.SimpleModelVo;
import com.sdkj.recruit.vo.UserLabelVo;
import com.sdkj.recruit.vo.UserVo;
import com.sdkj.recruit.vo.WorkExperienceVo;

@Controller
@Path("/user")
public class UserController {

	@Autowired
	private Mapper mapper;

	@Autowired
	private IUserService userService;

	@Autowired
	private IShareService shareService;

	private static final Logger logger = Logger.getLogger(LoginController.class);

	private static final PropertiesUtil propertiesUtil = new PropertiesUtil("config.properties");

	@Autowired
	private IQiNiuService qiNiu;

	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	@Path("/updatePassword")
	public ResultData<Object> updatePassword(@FormParam("userId") final String userId,
			@FormParam("oldPassword") final String oldPassword, @FormParam("newpassword") final String newpassword,
			@Context final HttpServletRequest request) {

		ResultData<Object> resultData = new ResultData<Object>();

		UserVo user = userService.queryUserById(userId);

		String oldpsw = generalPassword(user.getUserName(), oldPassword);

		if (!oldpsw.equals(user.getPassword())) {
			resultData.setResCode(ResultCode.FAILTURE);
			resultData.setMsg("原始密码不正确");
			return resultData;
		}

		String newpsw = generalPassword(user.getUserName(), newpassword);
		userService.updatePassword(userId, newpsw);
		resultData.setResCode(ResultCode.SUCCESS);
		return resultData;
	}

	/**
	 * 删除用户
	 * 
	 * @param userId
	 * @param req
	 */
	@Path("/{userId}/deleteUser")
	@GET
	public ResultData<Object> deleteUser(@PathParam("userId") final String userId, @Context HttpServletRequest req) {
		try {
			userService.deleteUser(userId);
			return ResultCode.success("删除用户成功", null);
		} catch (Exception e) {
			return ResultCode.error("删除用户失败", null);
		}
	}
	
	
	@Path("/saveUserPic")
	@POST
	public ResultData<Object> saveUserPic(@Context HttpServletRequest request) {

		String compress = "";
		try {

			String cropX = request.getParameter("cropX");
			String cropY = request.getParameter("cropY");
			String cropW = request.getParameter("cropW");
			String cropH = request.getParameter("cropH");

			final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(request);
			if (uploadFiles.length == 0) {
				return ResultCode.error("上传文件不能为空", null);
			}
			File file = uploadFiles[0].getInternalFile();
			String compressPicPath = propertiesUtil.getProperty("compressPicPath") + "/" + new Date().getTime()
					+ ".jpg";

			ImageUtil.cut(file.getPath(), compressPicPath, Integer.valueOf(cropX), Integer.valueOf(cropY),
					Integer.valueOf(cropW), Integer.valueOf(cropH), "jpg");
			compress = qiNiu.upload(new File(compressPicPath));
			return ResultCode.success("上传成功", compress);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return ResultCode.success("上传失败", compress);
	}

	/**
	 * 后台使用
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@Path("/queryUserList")
	@GET
	public ResultData<Object> queryUserList(@QueryParam("pageNo") final int pageNo,
			@QueryParam("pageSize") final int pageSize, @QueryParam("keyWord") final String keyWord,
			@Context HttpServletRequest req) {

		try {

			SimpleModelVo vo = new SimpleModelVo();
			List<UserVo> list = userService.queryUserList(pageNo, pageSize, keyWord);
			vo.setUserList(list);
			vo.setCount(userService.queryAllUserCount(keyWord));
			return ResultCode.success("获取用户成功", vo);
		} catch (Exception e) {
			return ResultCode.error("获取用户失败", null);
		}
	}
	
	

	/**
	 * 保存简历信息
	 * 
	 * @param resumeVo
	 * @param req
	 * @return
	 */
	@Path("/saveResume")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> saveResume(final ResumeVo resumeVo, @Context HttpServletRequest req) {

		return userService.saveResume(resumeVo);
	}
	
	
	@Path("/saveUserLabel")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> saveUserLabel(final UserLabelVo labelVo, @Context HttpServletRequest req) {

		return userService.saveUserLabel(labelVo);
	}
	
	
	@Path("/deleteLabel/{id}")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> deleteLabel(@PathParam("id") final String  id, @Context HttpServletRequest req) {

		return userService.deleteLabel(id);
	}
	
	
	/**
	 * 增加教育经历
	 * @param workExperienceVo
	 * @param req
	 * @return
	 */
	@Path("/addeducationalExperience")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> addeducationalExperience(final EducationalExperienceVo educationalExperienceVo, @Context HttpServletRequest req) {

		return userService.addeducationalExperience(educationalExperienceVo);
	}
	
	
	/**
	 * 增加工作经历
	 * @param workExperienceVo
	 * @param req
	 * @return
	 */
	@Path("/addWorkExperience")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> addWorkExperience(final WorkExperienceVo workExperienceVo, @Context HttpServletRequest req) {

		return userService.addWorkExperience(workExperienceVo);
	}
	
	/**
	 * 跟新工作经历
	 * @param workExperienceVo
	 * @param req
	 * @return
	 */
	@Path("/updateWorkExperience")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> updateWorkExperience(final WorkExperienceVo workExperienceVo, @Context HttpServletRequest req) {

		return userService.updateWorkExperience(workExperienceVo);
	}
	
	/**
	 * 跟新教育经历
	 * @param workExperienceVo
	 * @param req
	 * @return
	 */
	@Path("/updateEducationalExperience")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> updateEducationalExperience(final EducationalExperienceVo educationalExperienceVo, @Context HttpServletRequest req) {

		return userService.updateEducationalExperience(educationalExperienceVo);
	}
	
	
	@Path("/deleteEducationalExperience/{id}")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> deleteEducationalExperience(@PathParam("id") final String  id, @Context HttpServletRequest req) {

		return userService.deleteEducationalExperience(id);
	}
	
	
	@Path("/deleteWorkExperience/{id}")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> deleteWorkExperience(@PathParam("id") final String  id, @Context HttpServletRequest req) {

		return userService.deleteWorkExperience(id);
	}

	/**
	 * 更新简历，基本信息+自我介绍
	 * 
	 * @param resumeVo
	 * @param req
	 * @return
	 */
	@Path("/updateResume")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> updateResume(final ResumeVo resumeVo, @Context HttpServletRequest req) {

		if(StringUtil.isEmptyString(resumeVo.getResumeId())) {
			
			return userService.saveResume(resumeVo);
		}
		return userService.updateResume(resumeVo);
	}

	/**
	 * 删除简历
	 * 
	 * @param resumeId
	 * @param req
	 * @return
	 */
	@Path("/deleteResume/{resumeId}")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> deleteResume(@PathParam("resumeId") final String resumeId,
			@Context HttpServletRequest req) {

		return userService.deleteResume(resumeId);
	}

	/**
	 * 获取简历
	 * 
	 * @param resumeId
	 * @param req
	 * @return
	 */
	@Path("/queryResume/{resumeId}")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> queryResume(@PathParam("resumeId") final String resumeId,
			@Context HttpServletRequest req) {

		return userService.queryResume(resumeId);
	}
	
	
	
	
	/**
	 * 发送简历
	 * 
	 * @param userId
	 * @param resumeId
	 * @param req
	 * @return
	 */
	@Path("/sendResume")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> sendResume(final CompanyResumeVo companyResumeVo,
			@Context HttpServletRequest req) {

		return userService.sendResume(companyResumeVo.getUserId(), companyResumeVo.getResumeId(), companyResumeVo.getCompanyId(),companyResumeVo.getPositionId());
	}

	/**
	 * 后台增加用户
	 * 
	 * @param userVo
	 * @param req
	 * @return
	 */
	@Path("/saveUser")
	@POST
	public ResultData<Object> saveUser(final UserVo userVo, @Context HttpServletRequest req) {
		try {

			if (StringUtil.isEmptyString(userVo.getUserName()) || StringUtil.isEmptyString(userVo.getNickName())
					|| StringUtil.isEmptyString(userVo.getPassword())) {
				return ResultCode.error("用户信息不能为空，新增失败", null);
			}
			User u = userService.queryUserByName(userVo.getUserName().trim());
			if (u != null) {
				return ResultCode.error("该用户名已经存在", null);
			}

			/*
			 * if(!StringUtil.isEmptyString(userVo.getMobile())){ User u1
			 * =userService.queryUserByPhone(userVo.getMobile()); if(u1!=null){ return
			 * ResultCode.error("手机号已经存在", userVo); } }
			 */

			userVo.setCreateDate(new Date());
			userVo.setUserId(new RandomUtil().getRandomId());
			String psw = generalPassword(userVo.getUserName(), userVo.getPassword());

			userVo.setPassword(psw);
			userVo.setAccountStatus(1);
			return userService.register(mapper.map(userVo, User.class));
		} catch (Exception e) {
			return ResultCode.error("新增用户失败", userVo);
		}
	}

	/**
	 * 更新用户状态
	 * 
	 * @param userId 用户ID
	 * @param status 账号状态 0：正常 1：停用
	 * @param req
	 */
	@Path("/updateStatus")
	@GET
	public void updateStatus(@QueryParam("userId") final String userId, @QueryParam("status") final int status,
			@Context HttpServletRequest req) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("accountStatus", status);
		userService.updateUserByUserId(userId, map);
	}

	/**
	 * 注册用户
	 * 
	 * @param userVo
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/register")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> register(final UserVo userVo, @Context HttpServletRequest request)
			throws IOException, Exception {

		ResultData<Object> resultData = new ResultData<Object>();
		// 参数验证
		if (StringUtil.isEmptyString(userVo.getMobile()) || StringUtil.isEmptyString(userVo.getDeveiceId())) {
			resultData.setMsg("请求参数为空，请检查参数。");
			resultData.setResCode(ResultCode.FAILTURE);
			return resultData;
		}

		// 手机号注册
		User u = userService.queryUserByPhone(userVo.getMobile());
		if (u != null) {
			resultData.setMsg("该手机号已经被注册，请从新输入。");
			resultData.setResCode(ResultCode.FAILTURE);
			return resultData;
		}
		// 返回结果
		UserVo resultVo = new UserVo();
		User user = new User();
		user.setUserId(new RandomUtil().getRandomId());

		String psw = generalPassword(userVo.getMobile(), userVo.getPassword());
		user.setPassword(psw);
		// 客户端类型 1:网页,2：Android ,3：IOS
		int clientFlag = getClientFlag(request);

		Date lastLoginTime = new Date();
		String accessToken = MD5Util.string2MD5(userVo.getMobile() + new Date().getTime());
		user.setAccessToken(accessToken);
		user.setExpireTime(7776000);
		user.setLastLoginTime(lastLoginTime);
		user.setOnline(false);
		UserDeviceAccess deviceAccess = new UserDeviceAccess();
		Map<Integer, UserDeviceAccess> userDevice = new HashMap<Integer, UserDeviceAccess>();
		deviceAccess.setDeviceId(userVo.getDeveiceId());
		deviceAccess.setClientFlag(clientFlag);
		deviceAccess.setLastLoginTime(lastLoginTime);
		userDevice.put(clientFlag, deviceAccess);
		user.setTokenTime(lastLoginTime);
		user.setCreateDate(lastLoginTime);
		userService.register(user);
		resultVo = mapper.map(user, UserVo.class);
		resultData.setResCode(ResultCode.SUCCESS);
		resultData.setObj(resultVo);
		return resultData;
	}

	/**
	 * 获取用户详情
	 * 
	 * @param userId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/getUserDetailById/{userId}")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> getUserDetailById(@PathParam("userId") final String userId,
			@Context final HttpServletRequest request) throws IOException, Exception {

		ResultData<Object> resultData = new ResultData<Object>();
		UserVo u = userService.queryUserById(userId);
		if (u == null) {
			resultData.setResCode(ResultCode.FAILTURE);
			resultData.setMsg("用户不存在");
			return resultData;
		}
		//u.setShareCount(Integer.valueOf(String.valueOf(shareService.queryShareCount(u.getUserId()))));
		resultData.setResCode(ResultCode.SUCCESS);
		resultData.setObj(u);
		return resultData;
	}

	/**
	 * 根据员工编号获取信息
	 * 
	 * @param userId
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	@Path("/getUserByCode/{emCode}")
	@GET
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> getUserByCode(@PathParam("emCode") final String emCode,
			@Context final HttpServletRequest request) throws IOException, Exception {

		ResultData<Object> resultData = new ResultData<Object>();
		UserVo u = userService.queryUserByEmCode(emCode);
		if (u == null) {
			resultData.setResCode(ResultCode.FAILTURE);
			resultData.setMsg("用户不存在");
			return resultData;
		}
		u.setShareCount(Integer.valueOf(String.valueOf(shareService.queryShareCount(u.getUserId()))));
		resultData.setResCode(ResultCode.SUCCESS);
		resultData.setObj(u);
		return resultData;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param userVo
	 * @param req
	 * @return
	 */
	@Path("/updateUser")
	@POST
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ResultData<Object> updateUser(final UserVo userVo, @Context final HttpServletRequest req,
			@Context final HttpServletResponse resq) {

		ResultData<Object> result = new ResultData<>();

		Map<String, Object> property = new HashMap<String, Object>();
		final HttpSession session = req.getSession();
		if (StringUtil.isNotEmptyString(userVo.getUserPicUrl())) {
			property.put("userPicUrl", userVo.getUserPicUrl());
		}

		if (StringUtil.isNotEmptyString(userVo.getNickName())) {
			property.put("nickName", userVo.getNickName());
		}

		if (StringUtil.isNotEmptyString(userVo.getUserName())) {
			property.put("userName", userVo.getUserName());
		}

		if (StringUtil.isNotEmptyString(userVo.getEmail())) {
			property.put("email", userVo.getEmail());
		}

		if (StringUtil.isNotEmptyString(userVo.getAddress())) {
			property.put("address", userVo.getAddress());
		}

		if (StringUtil.isNotEmptyString(userVo.getMobile())) {
			property.put("mobile", userVo.getMobile());
		}

		if (userVo.getUserType() > 0) {
			property.put("userType", userVo.getUserType());
		}
		if (userVo.getSex() > 0) {
			property.put("sex", userVo.getSex());
		}

		if (userVo.getGroupId() > 0) {
			property.put("groupId", userVo.getGroupId());
		}
		if (userVo.getPositionId() > 0) {
			property.put("positionId", userVo.getPositionId());
		}

		if (StringUtil.isNotEmptyString(userVo.getBirthDate())) {
			property.put("birthDate", userVo.getBirthDate());
		}

		userService.updateUserProperty(userVo.getUserId(), property);
		UserVo userVo1 = userService.queryUserById(userVo.getUserId());

		if (userVo1 != null) {
			User user = mapper.map(userVo1, User.class);
			result.setObj(userVo1);
			// 更新缓存
			session.setAttribute(Constants.LOGIN_SESSION_KEY, user);
		}
		result.setResCode(ResultCode.SUCCESS);
		return result;
	}

	/**
	 * 生成加密密码 手机号加密
	 * 
	 * @param mobile
	 * @param password
	 * @return
	 */
	private String generalPassword(final String userName, final String password) {
		String decryptStr = "";
		try {
			decryptStr = DESEncryption.decrypt(password, userName);
		} catch (IOException e) {
			logger.error("Error in decrypt. Reason: " + e.getMessage());
		} catch (Exception e) {
			logger.error("Error in decrypt. Reason: " + e.getMessage());
		}

		if (userName.indexOf("@") != -1) {
			String shortUserName = userName.substring(0, userName.indexOf("@"));
			return MD5Util
					.string2MD5(shortUserName.toLowerCase() + Constants.USER_KEY + MD5Util.string2MD5(decryptStr));
		} else {
			return MD5Util.string2MD5(userName.toLowerCase() + Constants.USER_KEY + MD5Util.string2MD5(decryptStr));
		}
	}

	/**
	 * 获取客户端类型
	 * 
	 * @param request
	 * @return
	 */
	private int getClientFlag(HttpServletRequest request) {
		return RequestUtils.getClientFlag(request);
	}
}
